package top.huhuiyu.myimages.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import top.huhuiyu.myimages.dao.TbImagesDAO;
import top.huhuiyu.myimages.entity.TbImages;
import top.huhuiyu.myimages.model.TbImagesModel;
import top.huhuiyu.myimages.util.JsonMessage;
import top.huhuiyu.myimages.util.PageBean;

@RestController
@RequestMapping("/images")
public class TbImagesController {
	@Autowired
	private TbImagesDAO tbImagesDAO;

	@RequestMapping("/query")
	public JsonMessage query(TbImagesModel model) throws Exception {
		PageBean page = model.getPage();
		PageHelper.startPage(page.getPageNumber(), page.getPageSize());
		Page<TbImages> list = (Page<TbImages>) tbImagesDAO.query();
		page.setPageInfo(list);
		JsonMessage message = JsonMessage.getSuccess("查询完成");
		message.putData("list", list);
		message.putData("page", page);
		return message;
	}

	private static final String SAVE_PATH = "C:\\projects\\MyImagesStatic\\html\\upload\\";
	private static final String SERVICE_PATH = "/upload/";

	@RequestMapping("/upload")
	public JsonMessage upload(TbImagesModel model, MultipartFile file) throws Exception {
		if (file == null) {
			return JsonMessage.getFail("没有上传文件");
		}
		if (!file.getContentType().startsWith("image/")) {
			return JsonMessage.getFail("只能上传图片");
		}
		// 处理文件信息
		model.getImages().setFilesize(file.getSize()); // 文件大小
		model.getImages().setMime(file.getContentType()); // 文件类型
		// 原始文件名 旧版本ie个傻逼会把完整路径传递上来
		model.getImages().setFilename(file.getOriginalFilename());
		// 处理保存的文件名
		String filename = UUID.randomUUID().toString(); // 随机名称
		model.getImages().setSavePath(SERVICE_PATH + filename);
		// 保存文件
		byte[] bytes = new byte[8 * 1024];
		InputStream is = file.getInputStream(); // 获取上传文件的输入流
		// 输入流
		OutputStream os = new FileOutputStream(new File(SAVE_PATH + filename));
		int len = is.read(bytes);
		while (len > 0) {
			os.write(bytes, 0, len);
			os.flush();
			len = is.read(bytes);
		}
		os.close();
		is.close();
		// 保存到数据库
		tbImagesDAO.add(model.getImages());
		JsonMessage message = JsonMessage.getSuccess("上传成功!");
		message.putData("info", model.getImages());
		return message;
	}

	@RequestMapping("/queryLast")
	public JsonMessage queryLast(TbImagesModel model) throws Exception {
		JsonMessage message = JsonMessage.getSuccess("查询完成");
		message.putData("list", tbImagesDAO.queryLast());
		return message;
	}

	@RequestMapping("/delete")
	public JsonMessage delete(TbImagesModel model) throws Exception {
		tbImagesDAO.delete(model.getImages());
		return JsonMessage.getSuccess("删除成功");
	}
	
}
